package captcha

import (
	"energy-amiot-platform/core"
	"energy-amiot-platform/model/response"
	"energy-amiot-platform/utils/respout"

	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

type VerifyCaptchaReq struct {
	Id   string `json:"id" form:"id" binding:"required"`
	Code string `json:"code" form:"code" binding:"required"`
}

var (
	moduleCode = 3
)

// 创建验证码
// @Tags 验证码管理
// @Summary 添加验证码
// @Description
// @version 1.0
// @Produce json
// @Router /captcha/generate [post]
// @Success 200 {object} response.Response{result=response.Captcha} "Ok"
func generate(ctx *gin.Context) {
	var handleCode = 1
	id, s, a, err := core.Captcha.Generate()
	if err != nil {
		respout.SendError(ctx, core.APP.Code, moduleCode, handleCode, 0, "解析异常", err, nil)
		return
	}

	respout.Ok(ctx, response.Captcha{
		Id:     id,
		Anwser: a,
		B64s:   s,
	})
}

// 校验验证码
// @Tags 验证码管理
// @Summary 校验验证码
// @Description
// @version 1.0
// @Router /captcha/verify [post]
// @Produce json
// @Param   id query string true			"id"
// @Param   code query string true			"code"
// @Success 204 "验证通过"
// @Failure 400 {object} response.Response{} "验证失败"
func verify(ctx *gin.Context) {
	var handleCode = 2
	reqDto := new(VerifyCaptchaReq)
	if err := ctx.ShouldBind(reqDto); err != nil {
		respout.SendError(ctx, core.APP.Code, moduleCode, handleCode, 0, "解析异常", err, nil)
		return
	}

	if core.Captcha.Verify(reqDto.Id, reqDto.Code, true) {
		respout.Ok(ctx, nil)
		return
	}

	respout.SendError(ctx, core.APP.Code, moduleCode, handleCode, 1, "执行异常", errors.Errorf("验证失败"), nil)
}
